package xjson

import (
	"encoding/json"

	"github.com/golang/snappy"
)

// Marshal marshals v into json bytes.
func Marshal(v interface{}, compress ...bool) ([]byte, error) {
	body, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}

	if len(compress) > 0 && compress[0] {
		return snappy.Encode(nil, body), nil
	}

	return body, err
}

// Unmarshal unmarshals data bytes into v.
func Unmarshal(data []byte, v interface{}) error {
	body, err := snappy.Decode(nil, data)
	if err != nil {
		return json.Unmarshal(data, v)
	}
	return json.Unmarshal(body, v)
}
